package com.gsn.poker.game;

import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.TweenCallback;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.gsn.chooseChannel.ChooseChannelScreen;
import com.gsn.chooseGame.ChooseGameScreen;
import com.gsn.chooseRoom.ChooseRoomScreen;
import com.gsn.common.CheckTimeout;
import com.gsn.common.CheckTimeout.ITimeoutListener;
import com.gsn.common.Settings;
import com.gsn.common.Settings.EDevEnviroment;
import com.gsn.dataCommon.ChannelModel;
import com.gsn.dataCommon.ConfigModel;
import com.gsn.dataCommon.GiftModel;
import com.gsn.dataCommon.ShopModel;
import com.gsn.dataCommon.TableModel;
import com.gsn.dataCommon.UserData;
import com.gsn.desktop.engine.ActorUtility;
import com.gsn.engine.mercurry.MercuryClient.IMercuryListener;
import com.gsn.engine.myplay.GsnGame;
import com.gsn.engine.myplay.GsnScreen;
import com.gsn.engine.utility.UtilityGettor;
import com.gsn.login.LoginScreen;
import com.gsn.name.NameEdit;
import com.gsn.name.SessionkeyZingMe;
import com.gsn.name.Sort;
import com.gsn.name.StatePortal;
import com.gsn.poker.asset.ChatTexture;
import com.gsn.poker.asset.FontTexture;
import com.gsn.poker.asset.PokerSound;
import com.gsn.poker.asset.PokerTexture;
import com.gsn.poker.asset.PortalTexture;
import com.gsn.poker.logic.CardGroupLogic;
import com.gsn.poker.logic.GameRule;
import com.gsn.poker.packet.CmdDefine;
import com.gsn.poker.packet.PacketFactory;
import com.gsn.poker.play.PlayScreen;
import com.gsn.poker.play.UserInfo;

public class PokerGame extends GsnGame implements IMercuryListener, ITimeoutListener {
	public PlayScreen playScreen;

	public LoginScreen loginScreen;

	public ChooseGameScreen chooseGameScreen;
	public ChooseChannelScreen chooseChannelScreen;
	public ChooseRoomScreen chooseRoomScreen;
	private String tag = "Poker Game";

	public List<JSONObject> jsonList = new ArrayList<JSONObject>();
	public GsnScreen testScreen;
	public float scale;
	public String gameName = "Pokerhk";
	public String statePortal = "";
	public boolean inGame;

	class MyThread implements Runnable {
		boolean stop = false;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			JSONObject json = null;
			String sess = null;
			System.out.println("gui len portal ");
			try {
				json = SessionkeyZingMe.getInfo();
				if (json == null) {
					try {
						sess = SessionkeyZingMe.getSessionkeyUser(UserData.name, UserData.passWord, true);
						UserData.sessionKey = sess;

						try {

							save();
							json = SessionkeyZingMe.getInfo();
							ConfigModel.portalJson = json;
							setChooseGameScreen();
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
							MyPoker.game.setLoginScreen();
						}
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						MyPoker.game.setLoginScreen();
					}
				} else {
					ConfigModel.portalJson = json;
					UserData.avatar = json.getString("headurl");
					setChooseGameScreen();
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				MyPoker.game.setLoginScreen();
			}

			if (stop)
				return;
		}

	}

	public static void getInfo() {

		try {
			CookieStore cookiesStore = new BasicCookieStore();
			cookiesStore.clear();
			HttpContext context = new BasicHttpContext();
			context.setAttribute(ClientContext.COOKIE_STORE, cookiesStore);

			HttpParams my_httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(my_httpParams, 1000);
			HttpConnectionParams.setSoTimeout(my_httpParams, 1000);
			HttpClient httpclient = new DefaultHttpClient(my_httpParams);

			HttpPost httpPost = new HttpPost();
			httpPost.setURI(new URI("http://myplay.apps.zing.vn/portal/Api.php?session_id=1F018988FF48F14A6FAC6D94"));
			HttpResponse respones = httpclient.execute(httpPost, context);

			HttpEntity entity = respones.getEntity();
			if (entity != null) {
				System.out.println("Response content Length" + entity.getContentLength());
				HttpEntity temp = respones.getEntity();
				if (temp != null) {
					HttpEntity e = new BufferedHttpEntity(temp);
					String responseBody = EntityUtils.toString(e, "UTF-8");
					System.out.println(" in ne : " + responseBody + "!!!");
					String s = responseBody;
					while (!(s.charAt(0) == '{')) {
						System.out.println("char 0 : " + s.charAt(0));
						s = s.substring(1);
					}
					// s = s.substring(2);
					System.out.println("s : " + s);
					JSONObject json = new JSONObject(s);
					System.out.println(" id : " + json.getInt("userid"));
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void create() {
		super.create();

		Gdx.app.log(tag, "ON CREATE");
		CheckTimeout.getInstance().listener = this;
		CardGroupLogic group = new CardGroupLogic(44, 45, 46, 24, 25);
		GameRule rule = new GameRule();

		System.out.println(rule.getGroupType(group));
		PokerSound.load();

		this.scale = 1;
		if (width == 320 && height == 240) {
			scale = (320f / 480 + 240f / 320) / 2.0f;

			// FontTexture.inst().scale = (320f / 800 + 240f/ 480) / 2f;
		} else if (width == 800 && height == 480) {
			scale = (800f / 480 + 480f / 320) / 2.1f;

		} else if (width == 480 && height == 320) {
			scale = 1;

		} else if (width >= 1000) {
			scale = (width / 320 + height / 480f) / 2.3f;
		} else {
			scale = (width / 320 + height / 480f) / 2.3f;
		}

		Gdx.app.log(tag, "Scale : " + scale);

		PortalTexture.inst().loadTexture();

		PokerTexture.inst().loadTexture();
		ChatTexture.inst().loadTexture();
		FontTexture.inst().loadTexture();

		try {
			// PortalTexture.inst().loadAll();
			// LobbyTexture.inst().loadAll();
			// PokerTexture.inst().loadAll();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		this.assetList.add(PortalTexture.inst());

		this.assetList.add(PokerTexture.inst());
		this.assetList.add(ChatTexture.inst());
		this.assetList.add(FontTexture.inst());

		playScreen = new PlayScreen(width, height);
		playScreen.assetNeedList.add(PokerTexture.inst());
		playScreen.assetNeedList.add(ChatTexture.inst());

		loginScreen = new LoginScreen(width, height);

		chooseGameScreen = new ChooseGameScreen(width, height);
		chooseGameScreen.assetNeedList.add(PortalTexture.inst());
		chooseGameScreen.assetNeedList.add(FontTexture.inst());

		chooseChannelScreen = new ChooseChannelScreen(width, height);
		chooseChannelScreen.assetNeedList.add(PortalTexture.inst());
		chooseChannelScreen.assetNeedList.add(FontTexture.inst());

		chooseRoomScreen = new ChooseRoomScreen(width, height);
		chooseRoomScreen.assetNeedList.add(PortalTexture.inst());
		chooseRoomScreen.assetNeedList.add(FontTexture.inst());

		loadPreference();
		if (UserData.sessionKey.equals(""))
			setScreen(loginScreen);
		else {
			Thread thread = new Thread(new MyThread());
			thread.start();

		}

		if (!Settings.onDT && Settings.mode > 0) {
			// MyPoker.client.connect();
		}
	}

	public void setChooseRoomScreen() {
		setScreen(chooseRoomScreen);
		statePortal = StatePortal.CHOOSE_ROOM;
		System.out.println("set chooseroom screen");
		UtilityGettor.inst().hideTextField(NameEdit.GOLD);
		UtilityGettor.inst().hideTextField(NameEdit.XU);
	}

	public void setChooseChannelScreen() {
		setScreen(chooseChannelScreen);
		UtilityGettor.inst().hideProgressDialog();
		statePortal = StatePortal.CHOOSE_CHANNEL;
		UtilityGettor.inst().visibleTextField(NameEdit.GOLD);
		UtilityGettor.inst().visibleTextField(NameEdit.XU);
		inGame = true;
	}

	public void setPlayScreen() {
		setScreen(playScreen);
		statePortal = StatePortal.IN_GAME;
	}

	public void setChooseGameScreen() {
		setScreen(chooseGameScreen);
		statePortal = StatePortal.CHOOSE_GAME;
		UtilityGettor.inst().hideTextField(NameEdit.NAME_USER);
		UtilityGettor.inst().hideTextField(NameEdit.PASS_USER);
		UtilityGettor.inst().hideTextField(NameEdit.GOLD);
		UtilityGettor.inst().hideTextField(NameEdit.XU);
		chooseGameScreen.setInfoUser();
		inGame = false;
	}

	public void setLoginScreen() {
		setScreen(loginScreen);
		// if(UtilityGettor.onMobile)
		// {
		// hien text nhap cho pass va username
		loadPreference();
		UtilityGettor.inst().visibleTextField(NameEdit.NAME_USER);
		UtilityGettor.inst().visibleTextField(NameEdit.PASS_USER);
		UtilityGettor.inst().setTextField(NameEdit.NAME_USER, UserData.name);
		UtilityGettor.inst().setTextField(NameEdit.PASS_USER, UserData.passWord);
		// }
	}

	@Override
	public void resize(int width, int height) {
		// TODO Auto-generated method stub

	}

	Boolean tmpSound = null;

	@Override
	public void pause() {
		Gdx.app.log(tag, "ON PAUSE");
		tmpSound = Settings.enableSound;
		Settings.enableSound = false;
		PokerTexture.inst().finishLoading();
	}

	@Override
	public void resume() {
		super.resume();
		Gdx.app.log(tag, "ON RESUME");
		if (tmpSound != null)
			Settings.enableSound = tmpSound;
		PokerTexture.inst().finishLoading();
		if (currentScreen instanceof ChooseGameScreen) {

		} else if (currentScreen instanceof ChooseChannelScreen) {
			MyPoker.client.send(PacketFactory.createEcho());
		} else if (currentScreen instanceof ChooseRoomScreen) {
			MyPoker.client.send(PacketFactory.createEcho());

		} else if (currentScreen instanceof LoginScreen) {

		} else if (currentScreen instanceof PlayScreen) {
			MyPoker.client.send(PacketFactory.createEcho());

		}
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stubs
		PokerTexture.inst().manager.dispose();
		PortalTexture.inst().manager.dispose();
		ChatTexture.inst().manager.dispose();
		FontTexture.inst().manager.dispose();

		PokerTexture._instance = null;
		PortalTexture._instance = null;
		ChatTexture._instance = null;
		FontTexture._instance = null;
		CheckTimeout.getInstance().cancel();
		CheckTimeout.instance = null;

		if (Settings.mode > 0 && !Settings.onDT)
			if (MyPoker.client != null)
				MyPoker.client.disconnect();
	}

	private static JSONObject createJSON() {
		JSONObject json = new JSONObject();
		try {
			json.put("ext", "Pokerhk");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return json;
	}

	@Override
	public void onConnected() {
		String session = UserData.sessionKey;

		if (Settings.enviroment == EDevEnviroment.QUICK_PLAY) {

		}

		if (session.length() == 0) {
			MyPoker.client.send("{\"handler\":\"login\",\"username\":\"" + "cuong" + (int) Math.random() * 1000 + "\",\"password\":\"dawdwad\"}");
		} else {

			JSONObject json = new JSONObject();
			try {

				json = createJSON().put("_cmd", 0);
				JSONObject params = new JSONObject();
				params.put("sessionKey", session);
				json.put("params", params);
				MyPoker.client.send(json);
				CheckTimeout.getInstance().update();

			} catch (JSONException e) {
				e.printStackTrace();

			}
		}
		MyPoker.client.send(PacketFactory.mobile());

	}

	@Override
	public void onDisconnected() {

		UtilityGettor.inst().hideProgressDialog();
		CheckTimeout.getInstance().lastSend = -1;
		DataProvider.isDisconect = true;
		if (currentScreen instanceof PlayScreen)
			playScreen.showDisconnectDlg();
		else if (currentScreen instanceof ChooseChannelScreen) {
			chooseChannelScreen.showDisconnectDlg();
		} else if (currentScreen instanceof ChooseRoomScreen) {
			chooseRoomScreen.showDisconnectDlg();
		} else if (currentScreen instanceof ChooseGameScreen) {
			if (statePortal.equals(StatePortal.CHOOSING_GAME))
				UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", true);
			statePortal = StatePortal.CHOOSE_GAME;
		}

	}

	@Override
	public void onReceived(String s) {
		//

	}

	// @Override
	public void onReceivedJson1(JSONObject json) {
		// TODO Auto-generated method stub

	}

	// @Override
	public void onReceivedJson(final JSONObject json) {
		int count;
		int err;
		CheckTimeout.getInstance().resetLastSend();
		try {
			if (json == null)
				return;
			if (json.has("cmdID"))
				// if (json.getInt("cmdID") != 203)
				// if (json.getInt("cmdID") != 211)
				if (json.getInt("cmdID") != 216)
					Gdx.app.log(tag, "time " + System.currentTimeMillis() + " --- receive : " + json);
			if (json.has("loginOK")) {
				if (json.getInt("loginOK") == 0)
					MyPoker.client.send(PacketFactory.createLogin());
				else
					Gdx.app.log(tag, "login faiulre");
				return;
			}
			int cmd;

			cmd = json.getInt("cmdID");
			int mode = Settings.mode;
			switch (cmd) {
			case CmdDefine.GET_USER_INFO_SUCCESS:

				JSONObject uInfo = json.getJSONObject("pInfo");
				UserData.gold = uInfo.getLong("bean");
				UserData.xu = uInfo.getInt("coin");
				UserData.name = uInfo.getString("uName");
				UserData.avatar = uInfo.getString("avtURL");
				UserData.myId = uInfo.getInt("uId");
				UserData.numSupport = uInfo.getInt("numSupport");
				MyPoker.client.send(PacketFactory.loadConfig());

				break;
			case CmdDefine.LOAD_CONFIG:

				count = 0;
				String name;
				long goldStart;
				long goldEnd;
				int leafStart = 0;
				int leafEnd = 0;
				long jackpot = 0;
				long jackpotLevel = 0;
				int comission = 0;
				int bets[] = null;

				int i;
				try {
					JSONObject config = json.getJSONObject("config");
					Iterator<String> keys = config.getJSONObject("Channel").keys();
					ConfigModel.channelModelList = new ChannelModel[config.getJSONObject("Channel").getInt("maxChannel")];
					ConfigModel.maxPerChannel = config.getJSONObject("Channel").getInt("maxUserPerChannel");
					while (keys.hasNext()) {
						String s = keys.next();
						Object jsonTemp = config.getJSONObject("Channel").get(s);
						if (jsonTemp instanceof JSONObject) {
							name = ((JSONObject) jsonTemp).getString("name");
							goldStart = ((JSONObject) jsonTemp).getLong("minGold");
							goldEnd = ((JSONObject) jsonTemp).getLong("maxGold");
							jackpot = ((JSONObject) jsonTemp).getLong("jackpot");
							jackpotLevel = ((JSONObject) jsonTemp).getLong("jackpotLevel");
							leafEnd = ((JSONObject) jsonTemp).getInt("leafEnd");
							leafStart = ((JSONObject) jsonTemp).getInt("leafStart");
							int personCount[] = null;
							personCount = new int[leafEnd - leafStart + 1];
							JSONArray arr = ((JSONObject) jsonTemp).getJSONArray("bets");
							bets = new int[arr.length()];
							for (i = 0; i < arr.length(); i++) {
								bets[i] = arr.getInt(i);

							}
							for (i = 0; i < personCount.length; i++) {
								personCount[i] = 0;
							}
							ConfigModel.getInstance().channelModelList[Integer.valueOf(s)] = new ChannelModel(name, goldStart, goldEnd, leafStart, leafEnd, jackpot, comission, jackpotLevel, bets, personCount);
							// them mot phong moi
						}

					}

					JSONObject array = config.getJSONObject("DailyGift");
					keys = array.keys();
					int MAX_GIFT = 5;
					GiftModel arrayGift[] = new GiftModel[100];
					count = 0;
					while (keys.hasNext()) {
						count++;
						String s = keys.next();
						JSONObject jsonTemp = (JSONObject) array.get(s);
						arrayGift[Integer.valueOf(s) - 1] = new GiftModel(jsonTemp.getInt("bean"), jsonTemp.getInt("coin"));
						// ConfigModel.getInstance().giftModelList[Integer.valueOf(s)
						// - 1] = new GiftModel(jsonTemp.getInt("bean"),
						// jsonTemp.getInt("coin"));

					}
					ConfigModel.getInstance().giftModelList = new GiftModel[count];
					for (i = 0; i < count; i++)
						ConfigModel.getInstance().giftModelList[i] = arrayGift[i];
					arrayGift = null;

					ConfigModel.shopModelList = new ShopModel[config.getInt("ShopGoldNum")];
					array = config.getJSONObject("ShopGold");
					keys = array.keys();
					count = 0;

					while (keys.hasNext()) {
						count++;
						String s = keys.next();
						JSONObject jsonTemp = (JSONObject) array.get(s);
						ConfigModel.getInstance().shopModelList[Integer.valueOf(s)] = new ShopModel(jsonTemp.getInt("gold"), jsonTemp.getInt("coin"));

					}

					ConfigModel.beanNeedSupport = config.getJSONObject("Support").getInt("beanNeedSupport");
					setChooseChannelScreen();
					chooseChannelScreen.updateEnterGame();

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				break;
			case CmdDefine.CMD_SELECT_CHANNEL:

				err = json.getInt("errorCode");
				if (err == 0) {
					try {
						ConfigModel.selectedLeaf = json.getInt("selectedLeaf");
						ConfigModel.jackpot = json.getLong("jackpot");
						JSONArray array;
						array = json.getJSONArray("leafUser");
						for (i = 0; i < array.length(); i++) {
							ConfigModel.channelModelList[ConfigModel.selectedChannel].personCount[i] = array.getInt(i);
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					ConfigModel.sort = Sort.NUM_MAX_MIN;
					setChooseRoomScreen();
					chooseRoomScreen.updateEnterGame();
				} else {
					chooseChannelScreen.showConnectFail();
				}

				break;
			case CmdDefine.REFESH_LIST_TABLE:
				ConfigModel.tableModelList.clear();
				JSONArray personCount;
				JSONArray tableId;
				JSONArray totalCount;
				JSONArray bet;
				JSONArray requiredPass;
				JSONArray minGold;
				JSONArray type;
				JSONArray tableIndex;
				JSONArray tableName;

				try {

					personCount = json.getJSONArray("personCount");
					tableId = json.getJSONArray("tableId");
					totalCount = json.getJSONArray("totalCount");
					bet = json.getJSONArray("bet");
					requiredPass = json.getJSONArray("requiredPass");
					minGold = json.getJSONArray("minGold");
					type = json.getJSONArray("type");
					tableIndex = json.getJSONArray("tableIndex");
					tableName = json.getJSONArray("tableName");

					for (i = 0; i < personCount.length(); i++) {

						ConfigModel.tableModelList.add(new TableModel(type.getInt(i), bet.getLong(i), ActorUtility.shortString(15, tableName.getString(i)), personCount.getInt(i), totalCount.getInt(i), requiredPass.getInt(i), tableIndex.getInt(i), tableId.getInt(i)));
					}
					ConfigModel.sort();
					chooseRoomScreen.updateRoom();

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case CmdDefine.SHOP_GOLD:
				chooseChannelScreen.showChangeGoldSuccess();
				break;
			case CmdDefine.CMD_JOIN_ROOM_SUCCESS:

				playScreen.jsonJoinRoom = json;
				setPlayScreen();
				UtilityGettor.inst().hideProgressDialog();
				break;
			case CmdDefine.CMD_NEW_USER_JOIN:
				if (statePortal != StatePortal.IN_GAME)
					return;
				int nChair = json.getInt("nChair");
				int regChair = json.getInt("regChair");
				UserInfo info = new UserInfo();
				JSONObject jp = json.getJSONObject("playerInfo");
				info.name = jp.getString("uName");
				info.id = jp.getInt("uId");
				info.gold = jp.getLong("bean");
				info.avatar = jp.getString("avtURL");
				int playerStatus = json.getInt("playerStatus");
				switch (playerStatus) {
				case 1:
					playScreen.boardLayer.setUserInfor(nChair, info);
					playScreen.boardLayer.setVisible(nChair, true);
					playScreen.boardLayer.updateThamGiaBtn();

					break;
				case 5:
					if (regChair >= 0) {
						playScreen.boardLayer.addViewer(info.id, info.name, info.gold, info.avatar, true);
						playScreen.boardLayer.setViewRegUser(regChair, info);
						playScreen.boardLayer.updateThamGiaBtn();
					} else
						playScreen.boardLayer.addViewer(info.id, info.name, info.gold, info.avatar, false);
					break;
				}
				break;
			case CmdDefine.CMD_USER_EXIT_ROOM:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("nChair");
				int id = json.getInt("uId");
				playScreen.boardLayer.userExit(nChair, id);
				break;
			case CmdDefine.CMD_NOTIFY_GAME_START:
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.start(json);
				break;
			case CmdDefine.CMD_NOTIFY_DAILY_GIFT:
				UserData.giftIndex = json.getInt("index");
				break;
			case CmdDefine.CMD_NOTIFY_PUBLIC_CARD:
				if (statePortal != StatePortal.IN_GAME)
					return;
				JSONArray card1 = json.getJSONArray("card1");
				JSONArray card2 = json.getJSONArray("card2");
				JSONArray card3 = json.getJSONArray("card3");
				count = 0;
				for (i = 0; i < 5; i++) {
					if (card1.getInt(i) != 52)
						count++;
				}
				if (count == 1)
					playScreen.boardLayer.showChonQuan(card1.getInt(playScreen.boardLayer.myChair), card2.getInt(playScreen.boardLayer.myChair));
				else {
					playScreen.boardLayer.notifyCard(card1, card2, card3);
				}
				break;
			case CmdDefine.CMD_NOTIFY_SHOW_FIRST_CARD:
				if (statePortal != StatePortal.IN_GAME)
					return;
				int[] cards = new int[5];
				JSONArray arr = json.getJSONArray("cardID");
				for (i = 0; i < 5; i++)
					cards[i] = arr.getInt(i);
				playScreen.boardLayer.showFirstCard(cards);
				break;

			case CmdDefine.CMD_NOTIFY_CHANGE_TURN:
				if (statePortal != StatePortal.IN_GAME)
					return;
				int playerTurn = json.getInt("playerTurn");
				playScreen.boardLayer.changeTurn(playerTurn, json);
				break;
			case CmdDefine.CMD_NOTIFY_FOLD:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("nChair");
				playScreen.boardLayer.fold(nChair);
				break;
			case CmdDefine.CMD_NOTIFY_GAME_RESULT:
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.endGame(json);
				break;
			case CmdDefine.CMD_NOTIFY_DEAL_CARD:
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.dealCard(json);
				break;
			case CmdDefine.CMD_NOTIFY_BET_MONEY:
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.betMoney(json);
				break;
			case CmdDefine.CMD_NOTIFY_SHOW_CARD:
				if (statePortal != StatePortal.IN_GAME)
					return;
				id = json.getInt("PlayerID");
				int card = json.getInt("cardID");
				playScreen.boardLayer.showCard(id, card);
				break;
			case CmdDefine.CMD_NOTIFY_GAME_END:
				if (statePortal != StatePortal.IN_GAME)
					return;
				// MyPoker.client.pause();
				MyPoker.game.call(new TweenCallback() {

					@Override
					public void onEvent(EventType type, BaseTween source) {
						// TODO Auto-generated method stub
						// MyPoker.client.resume();
						playScreen.boardLayer.newGameWhenEndGame();
					}
				}, 5f);

				break;
			case CmdDefine.CMD_SEND_MESSAGE:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("nChair");
				String msg = json.getString("message");
				playScreen.boardLayer.chat(nChair, msg);
				break;
			case CmdDefine.CMD_NOTIFY_KICK_FROM_ROOM:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("chair");
				int reason = json.getInt("reason");
				playScreen.boardLayer.kickRoom(nChair, reason);
				break;
			case CmdDefine.CMD_UPDATE_MONEY:
				id = json.getInt("uId");
				if (id == UserData.myId) {
					UserData.gold = json.getLong("bean");
					UserData.xu = json.getInt("coin");

					chooseChannelScreen.updateMoney();
					chooseRoomScreen.updateMoney();
				}
				playScreen.updateMoney(json);
				break;
			case 119:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("PlayerID");
				playScreen.boardLayer.boLuot(nChair);
				break;
			case 112:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("roomOwner");
				playScreen.boardLayer.updateRoomOwner(nChair);
				break;
			case 114:// view request
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.view(json);
				break;
			case 120: // end card
				// boolean success = json.getBoolean("success");
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.allCard(json);
				break;
			case 11: // base info
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.baseInfo(json);
				break;
			case 111: // auto start
				if (statePortal != StatePortal.IN_GAME)
					return;
				int time = json.getInt("autoStartTime");
				boolean isAuto = json.getBoolean("isAutoStart");
				if (isAuto) {
					playScreen.boardLayer.newGame();
					playScreen.boardLayer.autoStart(time);
				} else
					playScreen.boardLayer.stopAutoStart();

				break;
			case 117: // take chair result
				if (statePortal != StatePortal.IN_GAME)
					return;
				err = json.getInt("error");
				if (err == 0) {
					playScreen.boardLayer.regSuccess(json.getInt("uId"), json.getInt("chair"));

					if (json.getInt("uId") == UserData.myId) {
						playScreen.showTakeChair(true);
						playScreen.boardLayer.takeChairResult(true);
						playScreen.boardLayer.meViewToUser = true;
					}
				} else {
					if (json.getInt("uId") == UserData.myId)
						playScreen.showTakeChair(false);
				}
				break;
			case 118: // jackpot
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.jackpot(json);
				break;
			case 115: // update danh sach xem
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.updateUserInNewGame(json);
				break;

			case 121:
				if (statePortal != StatePortal.IN_GAME)
					return;
				nChair = json.getInt("chair");
				id = json.getInt("userID");
				playScreen.boardLayer.userExit(id);
				jp = json.getJSONObject("playerInfo");

				// UserInfo info = new UserInfo();
				info = new UserInfo();
				info.name = jp.getString("uName");
				info.id = jp.getInt("uId");
				info.gold = jp.getLong("bean");
				info.avatar = jp.getString("avtURL");

				playScreen.boardLayer.addViewer(info.id, info.name, info.gold, info.avatar, false);

				break;
			case 65:
				if (statePortal != StatePortal.IN_GAME)
					return;
				playScreen.boardLayer.chatEmotion(json);
				break;
			case CmdDefine.CREATE_ROOM:

				int requirePass = (json.getBoolean("requiredPass") ? 1 : 0);
				ConfigModel.tableModelList.add(new TableModel(json.getInt("type"), json.getLong("bet"), ActorUtility.shortString(15, json.getString("tableName")), 1, 1, requirePass, json.getInt("tableIndex"), json.getInt("tableId")));

				ConfigModel.sort();
				chooseRoomScreen.updateRoom();
				break;
			case CmdDefine.DELETE_ROOM:
				ConfigModel.deleteRoom(json.getInt("tableId"));
				chooseRoomScreen.updateRoom();
				break;
			case CmdDefine.CMD_UPDATE_ROOM_LIST:
				JSONArray array = json.getJSONArray("leafUser");
				for (i = 0; i < array.length(); i++) {
					ConfigModel.channelModelList[ConfigModel.selectedChannel].personCount[i] = array.getInt(i);
				}
				JSONArray personCount1 = null;
				JSONArray tableId1 = null;
				JSONArray totalCount1 = null;

				personCount1 = json.getJSONArray("personCount");
				tableId1 = json.getJSONArray("tableId");
				totalCount1 = json.getJSONArray("totalCount");
				ConfigModel.updateTable(tableId1, personCount1, totalCount1);
				chooseRoomScreen.updateRoomNum();
				chooseRoomScreen.chooseRoomLayer.updateLeaf();
				break;
			case CmdDefine.CMD_SUPPORT_BEAN:

				UserData.numSupport = json.getInt("numSuport");
				if (currentScreen instanceof ChooseChannelScreen) {
					chooseChannelScreen.showDialogString("Bạn đã nhận được " + ActorUtility.formatNumber(json.getInt("nBean")) + " gold trợ giúp từ hệ thống");
				} else if (currentScreen instanceof ChooseRoomScreen) {
					chooseRoomScreen.showDialog("Bạn đã nhận được " + ActorUtility.formatNumber(json.getInt("nBean")) + " gold trợ giúp từ hệ thống");
				}
				break;
			case CmdDefine.CMD_CREATE_ROOM:
				err = json.getInt("errorCode");
				statePortal = StatePortal.CHOOSE_ROOM;
				UtilityGettor.inst().hideProgressDialog();
				switch (err) {
				case 1:
					chooseRoomScreen.showDialog("Bạn không đủ tiền để vào bàn chơi này");

					break;
				case 2:

					chooseRoomScreen.showDialog("Phòng này đã đầy bàn chơi rồi nhé");
					break;
				case 3:

					chooseRoomScreen.showDialog("Bạn đã chọn sai mức cược");
					break;
				case 4:

					chooseRoomScreen.showDialog("Mỗi lần tạo bàn phải cách nhau 3 phút nhé");
					break;

				default:
					break;
				}

				break;
			case CmdDefine.CMD_QUICK_PLAY_FAIL:
				chooseRoomScreen.showMakeRoom();
				statePortal = StatePortal.CHOOSE_ROOM;
				UtilityGettor.inst().hideProgressDialog();
				break;
			case CmdDefine.CMD_JOIN_ROOM_FAIL:
				UtilityGettor.inst().hideProgressDialog();
				statePortal = StatePortal.CHOOSE_ROOM;
				try {
					reason = json.getInt("reason");
					switch (reason) {
					case 0:
						// thieu tien
						chooseRoomScreen.showDialog("Bạn không đủ tiền để vào bàn chơi này");
						break;
					case 1:

						chooseRoomScreen.showDialog("Bạn nhập sai mật khẩu");

						break;
					case 2:
						chooseRoomScreen.showDialog("Bàn chơi đã đủ người. Vui lòng chọn bàn chơi khác");
						break;
					case 3:
						chooseRoomScreen.showDialog("Bạn đã ở trong bàn chơi rồi");
						break;
					case 4:
						// sendNotification(NotificationNames.DELETED_ROOM);
						chooseRoomScreen.showDialog("Bàn này đã được xóa");

					default:
						break;
					}

				} catch (Exception e) {
					// TODO: handle exception
				}

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onException(Exception ex) {
		// TODO Auto-generated method stub
		if (statePortal.equals(StatePortal.IN_GAME)) {

		} else if (statePortal.equals(StatePortal.CHOOSE_GAME)) {

		} else if (statePortal.equals(StatePortal.CHOOSING_GAME)) {
			UtilityGettor.inst().hideProgressDialog();
			UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", false);
			statePortal = StatePortal.CHOOSE_GAME;
		}
	}

	@Override
	public void quitGame() {
		// TODO Auto-generated method stub
		if (playScreen.boardLayer.inGame && playScreen.boardLayer.myChair >= 0)
			playScreen.showQuitDlg();
	}

	public void loadPreference() {
		Preferences shareData = Gdx.app.getPreferences("portal");
		UserData.name = shareData.getString(UserData.NAME, "");
		UserData.passWord = shareData.getString(UserData.PASSWORD, "");
		UserData.save = shareData.getBoolean(UserData.SAVE_PASS, false);
		UserData.sessionKey = shareData.getString(UserData.SESSION_KEY, "");
		UserData.sound = shareData.getBoolean(UserData.SOUND, true);
		UserData.music = shareData.getBoolean(UserData.MUSIC, true);
		UserData.vibrate = shareData.getBoolean(UserData.VIBRATE, true);

	}

	public void save() {

		Preferences shareData = Gdx.app.getPreferences("portal");
		shareData.putString(UserData.NAME, UserData.name);
		shareData.putString(UserData.PASSWORD, UserData.passWord);
		shareData.putBoolean(UserData.SAVE_PASS, UserData.save);

		shareData.putString(UserData.SESSION_KEY, UserData.sessionKey);

		shareData.flush();
	}

	@Override
	public void onPing() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTimeOut() {
		// TODO Auto-generated method stub
		CheckTimeout.getInstance().lastSend = -1;
		if (currentScreen instanceof ChooseGameScreen) {
			UtilityGettor.inst().hideProgressDialog();
			UtilityGettor.inst().toast("Kiểm tra lại kết nối mạng", true);
		} else if (currentScreen instanceof ChooseChannelScreen) {
			UtilityGettor.inst().hideProgressDialog();
			chooseChannelScreen.showDisconnectDlg();
		} else if (currentScreen instanceof ChooseRoomScreen) {
			UtilityGettor.inst().hideProgressDialog();
			chooseRoomScreen.showDisconnectDlg();
		} else if (currentScreen instanceof PlayScreen) {
			UtilityGettor.inst().hideProgressDialog();
			playScreen.showDisconnectDlg();
		}
	}

	public void onBackPress() {
		if (currentScreen instanceof LoginScreen) {
			UtilityGettor.inst().endActivity();

		} else if (currentScreen instanceof ChooseGameScreen) {
			chooseGameScreen.hideAllLayer();
			chooseGameScreen.onBackPress();

		} else if (currentScreen instanceof ChooseChannelScreen) {
			chooseChannelScreen.hideAllLayer();
			setChooseGameScreen();

			if (MyPoker.client != null)
				MyPoker.client.disconnect();
		} else if (currentScreen instanceof ChooseRoomScreen) {
			MyPoker.client.send(PacketFactory.createExitChannel());
			chooseRoomScreen.hideAllLayer();
			setChooseChannelScreen();
		} else if (currentScreen instanceof PlayScreen) {
			playScreen.onBackPress();
		}
	}

}
